﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.IO;
using System.Xml;
using System.Runtime.Serialization.Json;
using WechatModule.Tool;
using WechatModule.Model;
using System.Text;
using WechatModule.Model;
using System.Web.UI;
using System.Web.Security;
using RgUtility.Common;


namespace WechatModule.API
{
    /// <summary>
    /// 基本api
    /// </summary>
    public class WechatBaseAPI
    {
        public static Dictionary<string, object> dictCach = new Dictionary<string, object>();
        private static System.Web.Script.Serialization.JavaScriptSerializer jsSerial = new System.Web.Script.Serialization.JavaScriptSerializer();
        /// <summary>
        /// 得到BaseToken
        /// </summary>
        /// <returns></returns>
        public static string GetAccessToken()
        {
            string accessToken = "accessToken";

            if (!dictCach.ContainsKey(accessToken) || dictCach[accessToken] == null)
                dictCach[accessToken] = new AccessToken();
            var token = (AccessToken)dictCach[accessToken];
            if (token.expires_in == 0 || (token.ExireseTime - DateTime.Now).Seconds > 120) //7200秒过期提前2分钟获取
            {

                string access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
                //获取access_token值
                string requestUrl = access_token_url.Replace("APPID", WechatGlobalVar.AppId).Replace("APPSECRET", WechatGlobalVar.AppSecret);
                var json = ReuqestTool.GetWechatJson(requestUrl);
                var tokenNew = jsSerial.Deserialize<AccessToken>(json);
                dictCach[accessToken] = tokenNew;
                token = tokenNew;
                #region 注释
                //WebResponse result = null;
                //WebRequest req = WebRequest.Create(requestUrl);
                //result = req.GetResponse();
                //Stream stream = result.GetResponseStream();
                //XmlDictionaryReader xmlReader = JsonReaderWriterFactory.CreateJsonReader(stream, XmlDictionaryReaderQuotas.Max);
                //xmlReader.Read();
                //String XMLString = xmlReader.ReadOuterXml();
                //stream.Close();
                //stream.Dispose();
                ////封装请求类   
                //XmlDocument doc = new XmlDocument();
                //doc.LoadXml(XMLString);
                //XmlElement rootElement = doc.DocumentElement;

                //string access_token = rootElement.SelectSingleNode("access_token").InnerText;
                #endregion
            }
            return token.access_token;
        }
        //获得关注的用户信息
        public static BizResult<UserInfo, Error> GetUserInfo(string OPENID)
        {
            BizResult<UserInfo, Error> br = new BizResult<Model.UserInfo, Model.Error>();
            string Str = ReuqestTool.GetWechatJson("https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + GetAccessToken() + "&openid=" + OPENID + "&lang=zh_CN");
            if ((Str + "").Contains("errcode"))
            {
                var error = jsSerial.Deserialize<Error>(Str);
                if (error != null)
                {
                    br.Data1 = error;
                    br.AddMessage(error.errmsg);
                    br.ResultState = BizState.Warning;

                } return br;
            }
            br.Data = jsSerial.Deserialize<UserInfo>(Str);
            return br;
        }

        /// <summary>
        /// 未测试
        /// </summary>
        /// <param name="menu">该参数暂时无效，如果想用请自己改，懒的改了累死了</param>
        public static Error CreateMenu(Menu menu)
        {
            string apiUrl = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";
            apiUrl = apiUrl.Replace("ACCESS_TOKEN", GetAccessToken());
            #region 注释
            /*
            string responeJsonStr = @"
{
   'button':
    [
        {
            'name':'供应商注册',
            'sub_button':
            [
                {
                    'type':'click',
                    'name':'本平台点赞xx',
                    'key':'V01_S01'
                },
                { 
                    'type':'click',
                    'name':'平台认证',
                    'key':'V01_S02'
                }
            ]
        }
    ]
}";*/
            #endregion
            string responeJsonStr = @"
{
   'button':
    [
        {
            'type':'view',
            'name':'供应商注册',
            'url':'" + WechatGlobalVar.WechatBtn0Url + @"'
        },
        {
            'type':'view',
            'name':'标准说明',
            'url':'" + WechatGlobalVar.WechatBtn1Url + @"'
        },
        {
            'type':'click',
            'name':'关于',
            'key':'V01_S03'
        }
    ]
}";
            byte[] bytes = Encoding.UTF8.GetBytes(responeJsonStr.Replace("'", "\"").ToString());
            WebRequest req = WebRequest.Create(apiUrl);

            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            req.ContentLength = bytes.Length;
            using (Stream reqSt = req.GetRequestStream())
            {
                reqSt.Write(bytes, 0, bytes.Length);
                reqSt.Flush();
            }
            using (var response = req.GetResponse())
            {
                using (StreamReader rea = new StreamReader(response.GetResponseStream()))
                {
                    return jsSerial.Deserialize<Error>(rea.ReadToEnd());
                }
            }
        }

        /// <summary>
        /// 验证签名
        /// </summary>
        /// <returns></returns>
        public static bool CheckSignature(Page page)
        {
            string signature = page.Request.QueryString["signature"];
            string timestamp = page.Request.QueryString["timestamp"];
            string nonce = page.Request.QueryString["nonce"];
            string[] ArrTmp = { WechatGlobalVar.Token, timestamp, nonce };
            Array.Sort(ArrTmp);     //字典排序
            string tmpStr = string.Join("", ArrTmp);
            tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");
            tmpStr = tmpStr.ToLower();
            if (tmpStr == signature)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 验证接口
        /// </summary>
        /// <param name="page"></param>
        public static void Valid(Page page)
        {
            string echoStr = page.Request.QueryString["echoStr"];
            if (CheckSignature(page))
            {
                if (!string.IsNullOrEmpty(echoStr))
                {
                    page.Response.Write(page.Server.HtmlEncode(echoStr));
                    page.Response.End();
                }
            }
        }
    }
}